package com.asjy.controller;

import com.asjy.po.Cart;
import com.asjy.po.CartItem;
import com.asjy.po.Product;
import com.asjy.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.enterprise.inject.New;
import javax.servlet.http.HttpSession;

/**
 * @Auther: lilinlin
 * @Date: 2021/4/15
 * @Description: com.asjy.controller
 * @version: 1.0
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    @Resource
    private ProductService productService;
    @Resource
    private HttpSession session;
    @RequestMapping("/toCart")
    public String toCart(){
        return "cart";
    }

    @RequestMapping("/addCart")
    @ResponseBody
    public String addCart(Integer pId,Integer count){
        //添加购物项
        CartItem cartItem = new CartItem();
        cartItem.setCount(count);
        //查询商品
        Product product = productService.getProductById(pId);
        cartItem.setProduct(product);

        //购物项添加到购物车中
        Cart cart = (Cart)session.getAttribute("cart");
        if(cart==null){
            cart = new Cart();
            cart.addCartItem(cartItem);
            session.setAttribute("cart",cart);
        }else{
            cart.addCartItem(cartItem);
        }
        return "ok";
    }

    @RequestMapping("/delCartItem")
    @ResponseBody
    public String delCartItem(Integer pId){
        Cart cart = (Cart)session.getAttribute("cart");
        Double total =  cart.delCartItem(pId);
        return total.toString();
    }

    @RequestMapping("/clearCart")
    @ResponseBody
    public String clearCart(){
        Cart cart = (Cart)session.getAttribute("cart");
        Double total =  cart.clearCart();
        return total.toString();
    }
    @RequestMapping("/changeCount")
    @ResponseBody
    public String changeCount(Integer count,Integer pId){
        Cart cart = (Cart)session.getAttribute("cart");
        Double total =  cart.changeCount(count,pId);
        return total.toString();
    }

}